#!/usr/bin/env python
# -*-   coding: utf-8 -*-
import os
import sys
import re
from argparse import ArgumentParser
import mysql
try:
    import xml.etree.CElementTree as ET
except:
    import xml.etree.ElementTree as ET

ROOT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
if ROOT_PATH not in sys.path:
    sys.path.insert(0, ROOT_PATH)

from epg.connect import get, post, json_load
from epg.log import LOG
from epg.epg import process_gdtv, process_tvsou

def get_channel(gid):
    epg = mysql.getLiveEpg(gid)
    if not epg:
        LOG.error('Channel gid not exists.')
        sys.exit(1)
    return epg['channel_id'], epg['origin']


def process(args):
    gid = args.gid
    date = args.date
    regex = r'^\d{4}-\d{2}-\d{2}'
    if not re.match(regex, date):
        LOG.error('Please enter the correct date format')
        sys.exit(1)
    channel, origin = get_channel(gid)
    if not channel:
        LOG.error('Please enter an existing channel.')
        sys.exit(1)
    data = dict()
    if origin == 'gdtv':
        data = process_gdtv(channel, date)
    elif origin == 'tvsou':
        data = process_tvsou(channel, date.replace('-', ''))

    if not data:
        LOG.error('Program acquisition failed')
        sys.exit(1)
    query = date + '%'
    for idx in range(len(data)):
        data[idx]['classes'] = 1
        data[idx]['subclass'] = 1
        data[idx]['gid'] = gid
        data[idx]['store_path'] = '/data/' + gid
    for program in data:
        mysql.UpdateEPG(gid, program['program_name'], program['time'], "/data/" + gid)
    sys.exit(0)


def main():
    parser = ArgumentParser()
    parser.add_argument('gid', type=str, help='enter channel gid')
    parser.add_argument('date', type=str, help='crawl date, eg: 2018-01-01')
    args = parser.parse_args()
    process(args)

if __name__ == '__main__':
    main()
